﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using DonnetSpeech;
using FastReport;
using Leadtools;
using Leadtools.Codecs;
using SmallERP.COM;
using SmallERP.FenPian.Forms;
using SmallERP.FenPian.IView;
using SmallERP.Bll;
using SmallERP.MODEL.FoundationModel;
using SmallERP.MODEL.FenPian;
using Leadtools.WinForms;
using Smallerp.Contracts.DataContracts;
using System.ServiceModel;
using Smallerp.Contracts;
using System.IO;

namespace SmallERP.FenPian.Presenter
{
    /// <summary>
    /// 界面上格子的状态
    /// </summary>
    public enum UCGridStatus
    {
        TimeOut,//超时
        Priority,//加急，可以再细分
        OutOver,//此单的所有片都已出完但还未全进格子
        Selected,//被选中,级别最高
        Normal//一般状态
    }
    public class MyDefineGrid
    {
        public UCGrid UCg { get; set; }
        public GridInfo_GridDCT gridInfo { get; set; }
    }
    public class FenPianPresenter
    {

        private IFenPianView _view;
        private FenPianBLL _bll;
        SpeekMsgDelegate dlSpeak;//发音
        Report fastReport = new Report();
        SpVoice Voice = new SpVoice();
        SpeechVoiceSpeakFlags SpFlags;
        private List<MyDefineGrid> _curSelectedGridList = new List<MyDefineGrid>();//当前选中的格子集
        [DllImport("USER32.dll")]
        static extern short GetKeyState(int nVirtKey);
        const int VK_CONTROL = 0x11;

        public FenPianPresenter(IFenPianView view)
        {
           
            try
            {
                _view = view;
                _view._proxyOperateDB = new ChannelFactory<IOperateDBFenPian>("IOperateDBFenPian");
                _view._OperateDb = _view._proxyOperateDB.CreateChannel();
                _bll = new FenPianBLL(_view._OperateDb);
                SelectSubArea();
            }
            catch (EndpointNotFoundException ex)
            {
                MessageBox.Show("无法连接到:" + DataTransfer.IPadress);
                Environment.Exit(1);
            }
            catch (Exception exx)
            {
                MessageBox.Show("网络错误：" + exx.Message);
                Environment.Exit(1);
            }
            dlSpeak = SpeekMsg;//发音
            //  dlPrint = PintGrid; //打印
            //加载报表
            fastReport.Load(Application.StartupPath + "\\Report\\分片小票.frx");

        }

        //选择分区信息
        private void SelectSubArea()
        {
            FrmSelectSubarea frm = new FrmSelectSubarea();
            if (DialogResult.OK == frm.ShowDialog()) { IniFrm(); }
        }
        int UGridWidth;
        int UGridHeigth;
        private Dictionary<int, MyDefineGrid> GirdControls;//存放所有格子信息
        private void IniFrm()
        {
            Size screenSize = _view.GetDisplaySize;//获取屏的工作区域
            //UGridWidth = screenSize.Width / DataTransfer.CurSubArea.WidthNum - 7;
            //UGridHeigth = (screenSize.Height - 60) / DataTransfer.CurSubArea.HeightNum - 7;
            UGridWidth = screenSize.Width / DataTransfer.CurSubArea.HeightNum - 7;
            UGridHeigth = (screenSize.Height - 60) / DataTransfer.CurSubArea.WidthNum - 7;

            int result = 0;
            List<GridInfo_GridDCT> listGrid = null;
            result = _bll.GetGridInfoBySubAreaId(DataTransfer.CurSubArea.SubAreaID, out listGrid);
            if (result == 0)//成功
            {
                //将GridInfo_GridDCT转化为UCGrid控件
                IntiUCGrid(listGrid);
                // SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一个为选中状态
                DisPlayGrid();
            }
            else if (result == -1)//没有找到格子信息
            {
                ShowMessage("未找到" + DataTransfer.CurSubArea.SubAreaName + "格子信息，请查看该格子配置");
                SelectSubArea();
            }
            else if (result == 1)//输入的参数不对
            {

            }
            else if (result == 3)//从数据库取数据时出错
            {

            }
        }
        /// <summary>
        /// 将GridInfo_GridDCT转换为UCGrid控件
        /// </summary>
        /// <param name="sourceGridInfo"></param>
        /// <returns></returns>
        private void IntiUCGrid(List<GridInfo_GridDCT> sourceGridInfo)
        {
            if (GirdControls == null)
            {
                GirdControls = new Dictionary<int, MyDefineGrid>();
            }
            //排序
            sourceGridInfo = sourceGridInfo.OrderBy(g => Convert.ToInt32(g.GridBaseInfo.GridName.Substring(1))).ToList();
            foreach (var item in sourceGridInfo)
            {
                GirdControls.Add(item.GridBaseInfo.GridId, new MyDefineGrid()
                {
                    UCg = CreateUcgGrid(item),
                    gridInfo = item
                });
            }
        }

        /// <summary>
        /// 根据格子的显示实体，得到要应的控件
        /// </summary>
        /// <param name="gInfo"></param>
        /// <returns></returns>
        private UCGrid CreateUcgGrid(GridInfo_GridDCT gInfo)
        {
            UCGrid ucg = new UCGrid()
            {
                GridId = gInfo.GridBaseInfo.GridId,
                GridName = gInfo.GridBaseInfo.GridName,
                //GridStatus = GetUCGridStatus(gInfo),
                Width = UGridWidth,
                Height = UGridHeigth,
                Dock = DockStyle.Fill
            };

            ReSetUCGrid(ucg, gInfo);

            return ucg;
        }
        /// <summary>
        /// 用格子信息重新初始化格子
        /// </summary>
        /// <param name="ucg"></param>
        /// <param name="gInfo"></param>
        private void ReSetUCGrid(UCGrid ucg, GridInfo_GridDCT gInfo)
        {
            ucg.GridStatus = GetUCGridStatus(gInfo);
            if (gInfo != null && gInfo.OrderInfo != null)
            {
                int inGrid = (int)Status.PhotoStatus.InGrid;
                ucg.CurPicCount = gInfo.OrderInfo.PhotoS.Where(p => p.Status == inGrid).Count();
                ucg.PicCout = gInfo.OrderInfo.PhotoS.Count;
                ucg.OrderProductName = gInfo.OrderInfo.OrderName;
                //ucg.ShopName = gInfo.OrderInfo.ShopName;

                #region 注册双击、单击事件
                #region 先取消再添加取消双击点击事件
                try
                {
                    ucg.DoubleClick -= ucg_DoubleClick;
                    ucg.Click -= ucg_Click;

                    ucg.labCout.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCout.Click -= new EventHandler(labCout_Click);

                    ucg.labCurr.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCurr.Click -= new EventHandler(labCout_Click);

                    ucg.labGridName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labGridName.Click -= new EventHandler(labCout_Click);

                    ucg.labProductName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labProductName.Click -= new EventHandler(labCout_Click);



                    ucg.label1.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.label1.Click -= new EventHandler(labCout_Click);
                }
                catch { }
                #endregion

                ucg.DoubleClick += new EventHandler(ucg_DoubleClick);
                ucg.Click += new EventHandler(ucg_Click);

                ucg.labCout.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labCout.Click += new EventHandler(labCout_Click);

                ucg.labCurr.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labCurr.Click += new EventHandler(labCout_Click);

                ucg.labGridName.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labGridName.Click += new EventHandler(labCout_Click);

                ucg.labProductName.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labProductName.Click += new EventHandler(labCout_Click);



                ucg.label1.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.label1.Click += new EventHandler(labCout_Click);

                #endregion
            }
            else
            {
                ucg.CurPicCount = 0;
                ucg.PicCout = 0;
                ucg.OrderProductName = "";

                #region 取消双击点击事件
                try
                {
                    ucg.DoubleClick -= ucg_DoubleClick;
                    ucg.Click -= ucg_Click;

                    ucg.labCout.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCout.Click -= new EventHandler(labCout_Click);

                    ucg.labCurr.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCurr.Click -= new EventHandler(labCout_Click);

                    ucg.labGridName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labGridName.Click -= new EventHandler(labCout_Click);

                    ucg.labProductName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labProductName.Click -= new EventHandler(labCout_Click);


                    ucg.label1.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.label1.Click -= new EventHandler(labCout_Click);
                }
                catch { }
                #endregion
            }
        }
        private void ReSetUCGrid(MyDefineGrid InGrid, GridInfo_GridDCT gInfo)
        {
            InGrid.UCg.GridStatus = GetUCGridStatus(gInfo);
            if (gInfo != null && gInfo.OrderInfo != null)
            {
                int inGrid = (int)Status.PhotoStatus.InGrid;
                InGrid.UCg.CurPicCount = gInfo.OrderInfo.PhotoS.Where(p => p.Status == inGrid).Count();
                InGrid.UCg.PicCout = gInfo.OrderInfo.PhotoS.Count;
                InGrid.UCg.OrderProductName = gInfo.OrderInfo.OrderName;
                //ucg.ShopName = gInfo.OrderInfo.ShopName;

                #region 注册双击、单击事件
                #region 先取消再添加取消双击点击事件
                try
                {
                    InGrid.UCg.DoubleClick -= ucg_DoubleClick;
                    InGrid.UCg.Click -= ucg_Click;

                    InGrid.UCg.labCout.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.labCout.Click -= new EventHandler(labCout_Click);

                    InGrid.UCg.labCurr.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.labCurr.Click -= new EventHandler(labCout_Click);

                    InGrid.UCg.labGridName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.labGridName.Click -= new EventHandler(labCout_Click);

                    InGrid.UCg.labProductName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.labProductName.Click -= new EventHandler(labCout_Click);



                    InGrid.UCg.label1.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.label1.Click -= new EventHandler(labCout_Click);
                }
                catch { }
                #endregion

                InGrid.UCg.DoubleClick += new EventHandler(ucg_DoubleClick);
                InGrid.UCg.Click += new EventHandler(ucg_Click);

                InGrid.UCg.labCout.DoubleClick += new EventHandler(labCout_DoubleClick);
                InGrid.UCg.labCout.Click += new EventHandler(labCout_Click);

                InGrid.UCg.labCurr.DoubleClick += new EventHandler(labCout_DoubleClick);
                InGrid.UCg.labCurr.Click += new EventHandler(labCout_Click);

                InGrid.UCg.labGridName.DoubleClick += new EventHandler(labCout_DoubleClick);
                InGrid.UCg.labGridName.Click += new EventHandler(labCout_Click);

                InGrid.UCg.labProductName.DoubleClick += new EventHandler(labCout_DoubleClick);
                InGrid.UCg.labProductName.Click += new EventHandler(labCout_Click);



                InGrid.UCg.label1.DoubleClick += new EventHandler(labCout_DoubleClick);
                InGrid.UCg.label1.Click += new EventHandler(labCout_Click);

                #endregion
            }
            else
            {
                InGrid.UCg.CurPicCount = 0;
                InGrid.UCg.PicCout = 0;
                InGrid.UCg.OrderProductName = "";
                InGrid.gridInfo.OrderInfo = null;

                #region 取消双击点击事件
                try
                {
                    InGrid.UCg.DoubleClick -= ucg_DoubleClick;
                    InGrid.UCg.Click -= ucg_Click;

                    InGrid.UCg.labCout.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.labCout.Click -= new EventHandler(labCout_Click);

                    InGrid.UCg.labCurr.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.labCurr.Click -= new EventHandler(labCout_Click);

                    InGrid.UCg.labGridName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.labGridName.Click -= new EventHandler(labCout_Click);

                    InGrid.UCg.labProductName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.labProductName.Click -= new EventHandler(labCout_Click);


                    InGrid.UCg.label1.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    InGrid.UCg.label1.Click -= new EventHandler(labCout_Click);
                }
                catch { }
                #endregion
            }
        }

        /// <summary>
        /// 用格子信息重新初始化格子
        /// </summary>
        /// <param name="ucg"></param>
        /// <param name="gInfo"></param>
        private void ReSetUCGrid(UCGrid ucg, GridInfo_GridDCT gInfo, MyDefineGrid inCurrGrid)
        {
            ucg.GridStatus = GetUCGridStatus(gInfo);
            if (gInfo != null && gInfo.OrderInfo != null)
            {
                inCurrGrid.gridInfo = gInfo;
                int inGrid = (int)Status.PhotoStatus.InGrid;
                ucg.CurPicCount = gInfo.OrderInfo.PhotoS.Where(p => p.Status == inGrid).Count();
                ucg.PicCout = gInfo.OrderInfo.PhotoS.Count;
                ucg.OrderProductName = gInfo.OrderInfo.OrderName;
                //ucg.ShopName = gInfo.OrderInfo.ShopName;

                #region 注册双击、单击事件
                #region 先取消再添加取消双击点击事件
                try
                {
                    ucg.DoubleClick -= ucg_DoubleClick;
                    ucg.Click -= ucg_Click;

                    ucg.labCout.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCout.Click -= new EventHandler(labCout_Click);

                    ucg.labCurr.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCurr.Click -= new EventHandler(labCout_Click);

                    ucg.labGridName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labGridName.Click -= new EventHandler(labCout_Click);

                    ucg.labProductName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labProductName.Click -= new EventHandler(labCout_Click);



                    ucg.label1.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.label1.Click -= new EventHandler(labCout_Click);
                }
                catch { }
                #endregion

                ucg.DoubleClick += new EventHandler(ucg_DoubleClick);
                ucg.Click += new EventHandler(ucg_Click);

                ucg.labCout.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labCout.Click += new EventHandler(labCout_Click);

                ucg.labCurr.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labCurr.Click += new EventHandler(labCout_Click);

                ucg.labGridName.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labGridName.Click += new EventHandler(labCout_Click);

                ucg.labProductName.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labProductName.Click += new EventHandler(labCout_Click);



                ucg.label1.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.label1.Click += new EventHandler(labCout_Click);

                #endregion
            }
            else
            {
                ucg.CurPicCount = 0;
                ucg.PicCout = 0;
                ucg.OrderProductName = "";

                #region 取消双击点击事件
                try
                {
                    ucg.DoubleClick -= ucg_DoubleClick;
                    ucg.Click -= ucg_Click;

                    ucg.labCout.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCout.Click -= new EventHandler(labCout_Click);

                    ucg.labCurr.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCurr.Click -= new EventHandler(labCout_Click);

                    ucg.labGridName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labGridName.Click -= new EventHandler(labCout_Click);

                    ucg.labProductName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labProductName.Click -= new EventHandler(labCout_Click);


                    ucg.label1.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.label1.Click -= new EventHandler(labCout_Click);
                }
                catch { }
                #endregion
            }
        }

        void labCout_Click(object sender, EventArgs e)
        {
            ucg_Click(((Control)sender).Parent, e);
        }

        void labCout_DoubleClick(object sender, EventArgs e)
        {
            ucg_DoubleClick(((Control)sender).Parent, e);
        }

        void ucg_Click(object sender, EventArgs e)//单击，就是选中
        {
            MyDefineGrid myGrid;
            GirdControls.TryGetValue(((UCGrid)sender).GridId, out myGrid);
            if (myGrid.gridInfo.OrderInfo != null)
            {
                SetGridSelected(myGrid);
            }

        }

        void ucg_DoubleClick(object sender, EventArgs e)
        {
            MyDefineGrid myGrid;
            GirdControls.TryGetValue(((UCGrid)sender).GridId, out myGrid);
            if (myGrid.gridInfo.OrderInfo != null)
            {
                SetGridSelected(myGrid);

                // 将格子中的图片信息绑定到右边滑出来的窗体中
                _view.ShowOrderDetail(myGrid);
            }

        }
        public void DisPlayGrid()
        {
            _view.DisPlayGrid(GirdControls.Values.Select(g => g.UCg).ToList());
        }
        /// <summary>
        /// 根据格子中照片的信息，得到格子相应的状态
        /// </summary>
        /// <param name="gInfo"></param>
        /// <returns></returns>
        private UCGridStatus GetUCGridStatus(GridInfo_GridDCT gInfo)
        {
            UCGridStatus resultStatus = UCGridStatus.Normal;
            if (gInfo != null && gInfo.OrderInfo != null)
            {

                if (gInfo.OrderInfo.PhotoCount == gInfo.OrderInfo.PhotoS.Count(p => p.Status == (int)Status.PhotoStatus.Printed || p.Status == (int)Status.PhotoStatus.InGrid))
                {
                    resultStatus = UCGridStatus.OutOver;
                }
                //if (gInfo.GridBaseInfo.FirstEnterTime.Subtract(DateTime.Now).TotalMinutes >= DataTransfer.CurSubArea.OutTimeAlarmTime)
                //{
                //    resultStatus = UCGridStatus.TimeOut;
                //}
            }

            return resultStatus;
        }
        /// <summary>
        /// 分配格子
        /// </summary>
        public void AssionGrid()
        {
            int photoBID = 0;

            photoBID = ConvertToPhotoID(_view.InpuPhotoCode);
            if (photoBID == 0)
            {
                MessageBox.Show("输入的字符不正确，请重新输入！");
                return;
            }
            PhotoDCT temPi = null;//在格子中的照片
            MyDefineGrid curGrid = new MyDefineGrid(); //当前格子
            string strPeak = string.Empty;//发音需要说的话
            bool isInGird = false;
            bool isNewGrid = false;

            // 先自已在格子中找一次，如果没有找到再从数据库中找
            foreach (var mg in GirdControls.Values)
            {
                if (mg.gridInfo.OrderInfo != null)
                {
                    temPi = mg.gridInfo.OrderInfo.PhotoS.Find(p => p.PhotoId == photoBID);
                    if (temPi != null)
                    {
                        if (temPi.Status == (int)Status.PhotoStatus.InGrid)
                        {
                            strPeak = mg.gridInfo.GridBaseInfo.GridName;
                        }
                        curGrid = mg;
                        isInGird = true;
                        break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(strPeak))
            {
                dlSpeak.BeginInvoke(strPeak, false, null, null);
                SetGridSelected(curGrid);//设置选中的格子
                return;
            }
            //在数据库中找
            GridInfo_GridDCT gridInfoGrid = new GridInfo_GridDCT();
            int GridID = 0;
            int intRtn = 0;
            if (_view.SelectModel == 0)
            {
                intRtn = _bll.AssinGrid(photoBID, out strPeak, out  gridInfoGrid, out GridID, DataTransfer.CurSubArea.SubAreaID);
            }
            else
            {
                intRtn = _bll.AssinGridForAutoCut(photoBID, out strPeak, out  gridInfoGrid, out GridID, DataTransfer.CurSubArea.SubAreaID);

            }
            if (intRtn == -1)
            {
                ShowMessage("照片不存在");
                return;
            }
            else if (intRtn == -2)
            {
                ShowMessage("照片未打印");
                return;
            }
            else if (intRtn == 2)
            {
                // ShowMessage("产品已经完成");//是否要打印 信息在gridInfoGrid中
                if (DialogResult.OK == MessageBox.Show("该产品已经完成是否重新打印？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    //PintGrid(gridInfoGrid);//打印小票

                    PintGrid(_bll.GetReCheckView(photoBID));
                }
                return;
            }
            else if (intRtn == 1)
            {
                strPeak += ",完成";
                SpeekMsg(strPeak, true);
                PintGrid(gridInfoGrid);//打印小票
                ReSetUCGrid(curGrid, null);
                // 产品完成要打印 信息在gridInfoGrid中
            }
            else if (intRtn == -3)
            {

                ShowMessage("没有可用格子");
            }
            else if (intRtn == 0)
            {
                SpeekMsg(strPeak, false);
                //正常分配格子分配格子的新照片//刷新缓存中的数据
                if (GridID != 0)
                {
                    GirdControls.TryGetValue(GridID, out curGrid);
                    if (curGrid != null)
                    {
                        curGrid.gridInfo.OrderInfo.PhotoS.FirstOrDefault(p => p.PhotoId == photoBID).Status =
                            (int)Status.PhotoStatus.InGrid;
                    }
                }
                ReSetUCGrid(curGrid, gridInfoGrid);


            }
            else if (intRtn == 3)
            {
                strPeak = strPeak + "完成";
                SpeekMsg(strPeak, true);
                PintGrid(gridInfoGrid);//打印小票
                //单张完成
            }
            else if (intRtn == 4)
            {
                SpeekMsg(strPeak, false);
                //正常新分配格子//吧数据存在缓存中
                GirdControls.TryGetValue(GridID, out curGrid);
                ReSetUCGrid(curGrid.UCg, gridInfoGrid, curGrid);
            }
            else if (intRtn == -5)
            {
                ShowMessage("请将该照片放至" + strPeak);
            }
            else
            {
            }



        }
        //验证输入照片ID
        private int ConvertToPhotoID(string strInput)
        {
            strInput = strInput.Trim();
            if (string.IsNullOrEmpty(strInput))
            {
                return 0;
            }
            string rtnStr = null;
            if (Regex.IsMatch(strInput, "^[0-9]*$"))//验证是否为数字
            {

                rtnStr = strInput;

            }
            else
            {
                rtnStr = "0";
            }
            return Convert.ToInt32(rtnStr);
        }
        #region 发音与打印
        private delegate void SpeekMsgDelegate(string strMsg, bool isNeedReadCompleted);

        /// <summary>
        /// 发音
        /// </summary>
        /// <param name="strMsg"></param>
        public void SpeekMsg(string strMsg, bool isNeedReadCompleted)
        {
            //更新界面的显示,"A1,此单已完成"
            string gridName = strMsg.Split(new char[] { ',' })[0];
            _view.ShowGridName(gridName);
            //Application.DoEvents();            




            if (isNeedReadCompleted)
            {
                Voice.Priority = SpeechVoicePriority.SVPAlert;
                SpFlags = SpeechVoiceSpeakFlags.SVSFDefault;


            }
            else
            {
                SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            }

            Voice.Speak(strMsg.Substring(1), SpFlags);//将A去掉直接读格子号



        }


        //用于异步调用打印的委托
        private delegate void PrintGridDeleGate(GridInfo_GridDCT gInfo);
        /// <summary>
        /// 打印格子里的内容
        /// </summary>
        /// <param name="gInfo"></param>
        public void PintGrid(GridInfo_GridDCT gInfo)
        {
            if (!Properties.Settings.Default.IsPrintTicket)
            {
                return;
            }
            if (!File.Exists(Application.StartupPath + "\\Report\\分片小票.frx"))
            {
                return;
            }
            //分为二部分：1、照片尺寸归类信息，用TABLE格式
            DataTable dt = new DataTable("PhotoSize");
            dt.Columns.Add("Path", typeof(string));
            dt.Columns.Add("Size", typeof(string));
            dt.Columns.Add("Num", typeof(int));

            //foreach (var pathItem in gInfo.OrderInfo.PhotoS.GroupBy(p => p.PhotoName.Substring(0, (p.PhotoName.LastIndexOf("\\") == -1 ? p.PhotoName.Length : p.PhotoName.LastIndexOf("\\")))))
            foreach (var pathItem in gInfo.OrderInfo.PhotoS.GroupBy(p =>p.ProductName))

            {
                foreach (var item in pathItem.GroupBy(p => p.SizeInch + "(in) (" + p.SizeCM + ")cm").ToList())
                {
                    dt.Rows.Add(new object[] { pathItem.Key, item.Key, item.Count() });
                }
            }

            dt.WriteXml(@"D:\分片小票数据.xml", XmlWriteMode.WriteSchema);
            //2、相应的头信息

            fastReport.RegisterData(dt, "PhotoSize");
            ////dt.WriteXml("");

            gInfo.OrderInfo.OrderName = gInfo.OrderInfo.OrderName.Replace('[', '(').Replace(']', ')');
            gInfo.OrderInfo.Remark = gInfo.OrderInfo.Remark.Replace('[', '(').Replace(']', ')');

            fastReport.SetParameterValue("orderID", gInfo.OrderInfo.OrderProductId.ToString());
            fastReport.SetParameterValue("priorityRemark", gInfo.OrderInfo.Priority);
            fastReport.SetParameterValue("orderProductName", gInfo.OrderInfo.OrderName);
            fastReport.SetParameterValue("orderRemark", gInfo.OrderInfo.Remark);
            if (gInfo.GridBaseInfo != null)
            {
                fastReport.SetParameterValue("gridName", gInfo.GridBaseInfo.GridName);
            }
            else
            {
                fastReport.SetParameterValue("gridName", "无");
            }

            fastReport.SetParameterValue("factoryName", "");


            fastReport.PrintSettings.ShowDialog = Properties.Settings.Default.IsShowPrintDialog;
            fastReport.Print();
            _view.CloseDetailPanel();//打印时关闭右边的详细窗体
        }

        //public void PintGrid(GridInfo_GridDCT gInfo)
        //{
        //    //分为二部分：1、照片尺寸归类信息，用TABLE格式
        //    DataTable dt = new DataTable("PhotoSize");
        //    dt.Columns.Add("Size", typeof(string));
        //    dt.Columns.Add("Num", typeof(int));

        //    foreach (var item in gInfo.OrderInfo.PhotoS.GroupBy(p => p.SizeInch + "(in) (" + p.SizeCM + ")cm").ToList())
        //    {
        //        dt.Rows.Add(new object[] { item.Key, item.Count() });
        //    }

        //    dt.WriteXml(@"D:\分片小票数据.xml", XmlWriteMode.WriteSchema);
        //    //2、相应的头信息

        //    fastReport.RegisterData(dt, "PhotoSize");
        //    ////dt.WriteXml("");

        //    gInfo.OrderInfo.OrderName = gInfo.OrderInfo.OrderName.Replace('[', '(').Replace(']', ')');
        //    gInfo.OrderInfo.Remark = gInfo.OrderInfo.Remark.Replace('[', '(').Replace(']', ')');

        //    fastReport.SetParameterValue("orderID", gInfo.OrderInfo.OrderProductId.ToString());
        //    fastReport.SetParameterValue("priorityRemark", gInfo.OrderInfo.Priority);
        //    fastReport.SetParameterValue("orderProductName", gInfo.OrderInfo.OrderName);
        //    fastReport.SetParameterValue("orderRemark", gInfo.OrderInfo.Remark);
        //    if (gInfo.GridBaseInfo != null)
        //    {
        //        fastReport.SetParameterValue("gridName", gInfo.GridBaseInfo.GridName);
        //    }
        //    else
        //    {
        //        fastReport.SetParameterValue("gridName", "无");
        //    }

        //    fastReport.SetParameterValue("factoryName", "测试工厂");


        //    //fastReport.PrintSettings.ShowDialog = _view.isShowPrintDialog;
        //    fastReport.Print();
        //    _view.CloseDetailPanel();//打印时关闭右边的详细窗体
        //}
        #endregion

        public void ShowMessage(string inStr)
        {
            MessageBox.Show(inStr, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void SetGridSelected(MyDefineGrid myGrid)
        {
            if (myGrid == null)
            {
                return;
            }
            int type = 1; //new
            if (_curSelectedGridList != null && _curSelectedGridList.Count > 0)
            {
                if (((GetKeyState(VK_CONTROL) & 0x8000) == 0))//没有按下CTRL键
                {
                    type = 1;
                    if (_curSelectedGridList.Count == 1 && _curSelectedGridList.Contains(myGrid))
                    {
                        myGrid.UCg.GridStatus = UCGridStatus.Selected;
                        return;
                    }
                    ReSetGridStatusAndCurCount(_curSelectedGridList);//还原上一些格子本来的状态
                }
                else//添加
                {
                    type = 0;
                }
            }

            if (myGrid.UCg.GridStatus == UCGridStatus.Selected)
            {
                if (type == 0)//按下CTRL
                {
                    if (_curSelectedGridList.Count > 1)
                    {
                        //从选择列表中删除此格子
                        SetSelectGridList(myGrid, 3);
                        //再还原其原来的状态
                        ReSetGridStatusAndCurCount(new List<MyDefineGrid>() { myGrid });//还原上一些格子本来的状态
                    }
                }
                else//没有按下CTRL
                {
                    SetSelectGridList(myGrid, type);
                    myGrid.UCg.GridStatus = UCGridStatus.Selected;
                }
            }
            else
            {
                SetSelectGridList(myGrid, type);
                myGrid.UCg.GridStatus = UCGridStatus.Selected;
            }

        }
        //重新改变格子的状态、颜色,当前数量等信息
        private void ReSetGridStatusAndCurCount(List<MyDefineGrid> myGrids)
        {
            foreach (var myGrid in myGrids)
            {
                myGrid.UCg.GridStatus = GetUCGridStatus(myGrid.gridInfo);
                if (myGrid.gridInfo == null || myGrid.gridInfo.OrderInfo == null)
                {
                    myGrid.UCg.CurPicCount = 0;
                }
                else
                {
                    myGrid.UCg.CurPicCount = myGrid.gridInfo.OrderInfo.PhotoS.Count(p => p.Status == (int)Status.PhotoStatus.InGrid);
                }
            }
        }
        /// <summary>
        /// 根据点击选中时的操作怎样向选中_curSelectedGridList添加数据
        /// </summary>
        /// <param name="selectedGrids"></param>
        /// <param name="type">0:add,1:new,2:删除</param>
        private void SetSelectGridList(MyDefineGrid selectedGrid, int type)
        {
            if (type == 0)
            {
                if (!_curSelectedGridList.Contains(selectedGrid))
                {
                    _curSelectedGridList.Add(selectedGrid);
                }

            }
            else if (type == 1)
            {
                _curSelectedGridList.Clear();
                if (selectedGrid != null)
                {
                    _curSelectedGridList.Add(selectedGrid);

                }
            }
            else if (type == 3)//从列表中删除
            {
                _curSelectedGridList.Remove(selectedGrid);
            }
            // SetFrmBtnEnable();
        }

        delegate List<RasterImageListItem> ShowImgInFrmDelegate();
        // <summary>
        /// 得到被选中的格子的图片的略缩图
        /// </summary>
        /// <returns></returns>
        internal void GetImageList()
        {
            ShowImgInFrmDelegate dlShowImg = ShowImgInFrm;
            IAsyncResult rl = dlShowImg.BeginInvoke(null, null);
            while (!rl.IsCompleted)
            {
                _view.SetProcessGo();
                Thread.Sleep(200);
            }
            _view.ShowImg(dlShowImg.EndInvoke(rl));
            _view.SetProcessOver();

        }

        //在界面中显示图片
        private List<RasterImageListItem> ShowImgInFrm()
        {
            //  List<RasterImage> listImg = new List<RasterImage>();
            List<RasterImageListItem> listItems = new List<RasterImageListItem>();
            RasterCodecs codecs = null;
            MyDefineGrid myGrid = _curSelectedGridList.First();
            if (myGrid.gridInfo.OrderInfo != null)
            {
                foreach (var pi in myGrid.gridInfo.OrderInfo.PhotoS.Where(p => p.Status != (int)Status.PhotoStatus.InGrid).ToList())
                {
                    if (pi.Image == null)
                    {
                        try
                        {
                            if (codecs == null)
                            {
                                RasterCodecs.Startup();
                                codecs = new RasterCodecs();
                            }
                            //pi.Image = GetStampPic(pi.PicPath, codecs);
                           //pi.ImageItem = GetItemPic(pi.PicPath, codecs, pi.PhotoId);
                            //pi.Image.

                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                    //listImg.Add(pi.Image);
                    //listItems.Add(pi.ImageItem);
                }

                if (codecs != null)
                {
                    codecs.Dispose();
                    RasterCodecs.Shutdown();
                }
            }
            return listItems;
            //_view.ShowImg(listImg);
        }

        //得到图片的缩略图，如果没有缩略图就加载原图
        private RasterImageListItem GetItemPic(string picPath, RasterCodecs codecs, int inPhotoId)
        {
            RasterImageListItem rtmItrm = new RasterImageListItem();
            RasterImage image1 = null;
            CodecsThumbnailOptions options = CodecsThumbnailOptions.Default;
            options.LoadStamp = true;
            options.Resample = true;
            options.MaintainAspectRatio = false;
            try
            {
                image1 = codecs.ReadThumbnail(picPath, options, 1);
            }
            catch
            {
                options.LoadStamp = false;
                try
                {
                    image1 = codecs.Load(picPath);
                    //image1.
                }
                catch (Exception ex)
                {
                    MessageBox.Show("找不到图片,请确认图片是否被移走!/n/r" + ex.Message);
                }

            }

            //return image1;
            rtmItrm = new RasterImageListItem(image1, 1, inPhotoId.ToString());

            return rtmItrm;
        }


        //得到图片的缩略图，如果没有缩略图就加载原图
        private RasterImage GetStampPic(string picPath, RasterCodecs codecs)
        {

            RasterImage image1 = null;
            CodecsThumbnailOptions options = CodecsThumbnailOptions.Default;
            options.LoadStamp = true;
            options.Resample = true;
            options.MaintainAspectRatio = false;
            try
            {
                image1 = codecs.ReadThumbnail(picPath, options, 1);
            }
            catch
            {
                options.LoadStamp = false;
                try
                {
                    image1 = codecs.ReadThumbnail(picPath, options, 1);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("找不到图片,请确认图片是否被移走!/n/r" + ex.Message);
                }

            }

            return image1;
        }

        //强制打印选中的格子
        public void ForcePrint()
        {
            string shopGridName = string.Empty;
            if (DialogResult.Yes !=
                MessageBox.Show("确认需要强制打印格子中的照片？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                return;
            }



            if (_curSelectedGridList.Count != 1)
            {
                ShowMessage("请单选中需要打印的格子！");
                return;
            }
            MyDefineGrid grid = _curSelectedGridList.First();

            int intRtn = _bll.ForcePrintGrid(grid.gridInfo);
            if (intRtn == -2)
            {
                ShowMessage("连接数据库失败，请检查网络，稍后再试。");
            }
            else if (intRtn == -1)
            {
                ShowMessage("格子号错误");
            }
            else if (intRtn == 1)
            {
                ShowMessage("还有照片在拼版中不能打印");
            }

            else//执行成功 打印格子信息并打印
            {
                PintGrid(grid.gridInfo);//打印小票
                ReSetUCGrid(grid.UCg, null);
            }


            //grid.gridInfo.GridBaseInfo.GridId

        }
        /// <summary>
        /// 清空格子
        /// </summary>
        public void ClearSelectedGrid()
        {

            if (DialogResult.Yes == MessageBox.Show("确认要清空这些格子？", "警报", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                int countOld = _curSelectedGridList.Count;


                MyDefineGrid[] tempList = _curSelectedGridList.ToArray();
                foreach (MyDefineGrid grid in tempList)
                {
                    int result = _bll.ClearSelectedGrid(grid.gridInfo);
                    if (result == 0)//操作成功，更新内存数据中照片的状态
                    {
                        _curSelectedGridList.Remove(grid);

                        ReSetUCGrid(grid, null);

                    }
                }
                int countCurr = _curSelectedGridList.Count;
                if (countCurr == 0)
                {

                    SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));
                    //格子中不为空的任意一下
                    ShowMessage("清空成功！");
                }
                else if (countCurr != 0 && countCurr < countOld)
                {
                    //SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));
                    //格子中不为空的任意一下
                    ShowMessage("清空部分成功！");
                }
                else
                {
                    ShowMessage("清空失败！");
                }


            }

            _view.CloseDetailPanel();//打印时关闭右边的详细窗体
        }
        /// <summary>
        /// 条件清柜
        /// </summary>
        public void ConditionPriorityGrid()
        {
            int conditionNum = 0;
            int result = 0;


            FrmPhotoNum frmNum = new FrmPhotoNum();
            if (frmNum.ShowDialog() == DialogResult.OK)
            {
                conditionNum = Convert.ToInt32(frmNum.spinEditNum.Value);
            }
            else
            {
                return;
            }

            if (conditionNum == 0)
            {
                if (MessageBox.Show("是否需要将全部格子都清柜？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    result = _bll.PriorityPhoto(GirdControls.Values.Where(g => g.gridInfo.OrderInfo != null).Select(g => g.gridInfo).ToList(), 0);
                }
            }
            else
            {
                result = _bll.PriorityPhoto(GirdControls.Values.Where(g => g.gridInfo.OrderInfo != null).Select(g => g.gridInfo).ToList(), conditionNum);
            }

            if (result == 0)
            {
                ShowMessage("操作成功！");
            }
            else
            {
                ShowMessage("操作失败！");
            }
        }
        //选择清柜
        public void PrioritySelectedGird()
        {
            int result = 0;
            if (MessageBox.Show("是否将全部选中的格子清柜？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                result = _bll.PriorityPhoto(_curSelectedGridList.Where(g => g.gridInfo.OrderInfo != null).Select(g => g.gridInfo).ToList(), 0);
                if (result == 0)
                {
                    ShowMessage("操作成功！");
                }
                else
                {
                    ShowMessage("操作失败,稍候重试！");
                }
            }
        }
        //刷新格子中的数据
        public void RefreshData()
        {
            List<GridInfo_GridDCT> listGrid = null;
            int result = _bll.GetGridInfoBySubAreaId(DataTransfer.CurSubArea.SubAreaID, out listGrid);
            MyDefineGrid myGrid;
            foreach (var gInfo in listGrid)
            {
                GirdControls.TryGetValue(gInfo.GridBaseInfo.GridId, out myGrid);
                if (myGrid != null)
                {
                    myGrid.gridInfo = gInfo;
                    ReSetUCGrid(myGrid.UCg, gInfo);
                }
                myGrid = null;
            }
            myGrid = null;

            //清空那里有，但是刷新后没有的格子
            foreach (var notInGinfo in GirdControls.Values.Where(mg => mg.gridInfo.OrderInfo != null).Select(mg => mg.gridInfo).Except(listGrid).ToList())
            {                 //清空这些格子
                GirdControls.TryGetValue(notInGinfo.GridBaseInfo.GridId, out myGrid);
                if (myGrid != null)
                {
                    notInGinfo.OrderInfo = null;
                    ReSetUCGrid(myGrid.UCg, null);
                }
                myGrid = null;
            }
            myGrid = null;
            _curSelectedGridList.Clear();
            SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一下
        }

        public void ChangeAreas()
        {
            SelectSubArea();
        }
        public void Clear()
        {
            GirdControls.Clear();
        }
    }
}
